import pdfMake from 'pdfmake/build/pdfmake'
import pdfFonts from 'pdfmake/build/vfs_fonts'
import fs from 'fs';


// 字体
pdfMake.vfs = pdfFonts

class Pdf {
  // 传入核心
  constructor(options) {
    this.pdf = pdfMake.createPdf(options)
  }

  // 获取 data
  data() {
    return this.pdf.getDataUrl()
  }

  // base64 
  base64() {
    return this.pdf.getBase64()
  }

  // 获取 buffer 格式
  buffer() {
    return this.pdf.getBuffer()
  }

  // 获取 Blob 格式
  blob() {
    return this.pdf.getBlob()
  }

  // 获取 流格式
  stream() {
    return this.pdf.getStream()
  }
  
  // 下载
  down(name) {
    return this.pdf.download(name)
  }

  // 写出
  write(filename) {
    return new Promise((resolve, reject) => {
			this.stream().then(stream => {
				stream.pipe(fs.createWriteStream(filename))
				stream.on('end', () => {
					resolve()
				})
				stream.end()
			}, result => {
				reject(result)
			});
		})
  }
}

export default {
  load(options) {
    if(!options) return false

    return new Pdf(options)
  }
}